<template>
  <div class="app-container">
    <div v-show="type == 0 || type == 2">
      <el-row>
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input v-model="queryParams.projectNumber" style="width:165px" placeholder="请输入项目编号" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" style="width:170px" placeholder="请输入项目名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable style="width:155px" v-model="queryParams.startTime" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable style="width:155px" v-model="queryParams.endTime" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left:10px">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row style="margin-left:6px" :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-if="isTree">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleChange" v-if="!isTree"
                :disabled="single">确认</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table style="margin-left:10px" v-loading="loading" size="mini" height="400"
            :row-style="{ height: '30px' }" border :cell-style="{ padding: '0px' }" :data="projectInfoList"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column label="序号" type="index" align="center" prop="index" width="50" :index="indexMethod"
              :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="项目编号" align="center" prop="projectNumber" width="100"
              :show-overflow-tooltip="true" />
            <el-table-column label="项目名称" align="center" prop="projectName" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <!-- 使用按钮作为可点击元素，并绑定点击事件 -->
                <el-button size="small" @click="handleClick(scope.row, scope.$index + 1)" type="text">
                  {{ scope.row.projectName }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="项目负责人" align="center" prop="projectLeader" width="120"
              :show-overflow-tooltip="true" />
            <el-table-column label="立项方式" align="center" :formatter="typeFormat" prop="projectType" width="70"
              :show-overflow-tooltip="true" />
            <el-table-column label="计划开始时间" align="center" prop="startTime" width="95" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="计划结束时间" align="center" prop="endTime" width="95" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="状态" align="center" prop="state" width="65">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.project_status" :value="scope.row.state" />
              </template>
            </el-table-column>
            <el-table-column label="创建人" align="center" prop="creationName" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="creationTime" width="90" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" v-if="isTree">
              <template slot-scope="scope" v-if="scope.row.state == 0 || scope.row.state == 7">
                <el-button size="mini" type="text" icon="el-icon-check" @click="submitState(scope.row)"
                  v-if="scope.row.state == '0' && (scope.row.covenantId != '' && scope.row.covenantId != null)" title="提交"></el-button>
                <el-button size="mini" type="text" icon="el-icon-edit"
                  @click="handleUpdate(scope.row, scope.$index + 1)" v-if="scope.row.state == '0'" title="编辑"> </el-button>
                <el-button size=" mini" v-if="scope.row.state == '7'" type="text" icon="el-icon-folder-delete"
                  @click="handleNotRecipient(scope.row)" title="拒收">
                </el-button>
                <el-button size=" mini" v-if="scope.row.state == '7'" type="text" icon="el-icon-folder-checked"
                  @click="handleRecipient(scope.row)" title="接收">
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="isSale ? getList : listDeliverProject" />
        </el-col>
      </el-row>
    </div>
    <el-dialog :title="titleClass" :visible.sync="openMainClass" width="450px" append-to-body>
      <el-form ref="formClass" :model="formClass" :inline="true">
        <el-form-item label="主分类" prop="classificationId" label-width="80px">
          <treeselect v-model="formClass.classificationId" :options="optionData" placeholder="请选择主分类"
            style="width: 300px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClassForm()">保 存</el-button>
        <el-button @click="cancelClass">关 闭</el-button>
      </div>
    </el-dialog>
    <div v-if="type == 1">
      <Operate @change="close" :opt="edit" :id="id" :index="index" :classId="classId"></Operate>
    </div>
    <div v-if="type == 3">
      <Detail @change="closeDetail" :opt="edit" :id="id" :index="index">
      </Detail>
    </div>
  </div>
</template>

<script>
import { editState, editMainClass, listDeliverProject, otherProjectList, listProjectTree, getProjectInfo, delProjectInfo, addProjectInfo, selectProjectContract, updateProjectInfo } from "@/api/project/projectInfo";
import MainType from "@/components/MainType/index";
import Operate from "./operate.vue";
import Detail from "./detail.vue"
import { listType } from "@/api/maintype/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { MainType, Operate, Treeselect, Detail },
  dicts: ['project_status'],
  name: "ProjectInfo",
  props: {
    isTree: {
      type: Boolean,
      default: true
    },
    isEnterprise: {
      type: Boolean,
      default: true
    },
    isSale:{
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      titleClass: "修改主分类",
      optionData: null,
      openMainClass: false,
      typeCode: 'project',
      type: 0,
      opt: 'add',
      id: '',
      obj: null,
      index: null,
      classId: null,
      edit: 'edit',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        state: null,
        projectName: null,
        projectNumber: null,
        startTime: null,
        endTime: null,
        attackTime: null,
        completeTime: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      formClass: {},
    };
  },
  created() {
    this.listType()
    this.getList();
    if (!this.isSale){
     this.listDeliverProject();
    }else {
      this.getList();
    }
  },
  methods: {
    handleNotRecipient(row) {
      const id = row.projectId;
      this.$confirm('拒收项目"' + row.projectName + '"后，将会删除这条数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          recipientType: "no",
          classificationId: row.classificationId,
          projectId: id
        }
        updateProjectInfo(data).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消保存'
        });
      });
    },
    listDeliverProject(){
      this.loading = true;
      listDeliverProject(this.queryParams).then(response => {
        this.projectInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleRecipient(row) {
      const id = row.projectId;
      this.$confirm('是否接收"' + row.projectName + '"该项目，接收后项目进入立项状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          recipientType: "yes",
          classificationId: row.classificationId,
          projectId: id
        }
        updateProjectInfo(data).then(response => {
          this.$modal.msgSuccess("接收成功");
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消保存'
        });
      });
    },
    typeFormat(row, column) {
      var status = [];
      if (row.projectType == 1) {
        status.push("合同");
      } else if (row.projectType == 2) {
        status.push("产品");
      } else {
        status.push("外协");
      }
      return status.join("");
    },
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    //修改主分类
    editMainClass() {
      if (this.ids.length == 0) {
        this.$message.error("请选择要修改的信息！");
      } else {
        this.openMainClass = true;
      }
    },
    //获取树节点数据
    listType() {
      listType({ typeCode: 'project' }).then(res => {
        this.optionData = res.data;
      })
    },
    cancelClass() {
      this.openMainClass = false;
      this.resetClass();
    },
    submitClassForm() {
      if (this.formClass.classificationId == "undefined" || this.formClass.classificationId == "" || this.formClass.classificationId == null) {
        this.$message.error("请选择主分类！");
      } else {
        const params = {
          businessId: this.ids.toString(),
          mainClassId: this.formClass.classificationId,
        };
        editMainClass(params).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openMainClass = false;
          this.getList();
        });
      }
    },
    // 表单重置
    resetClass() {
      this.formClass = {
        classificationId: null,
      }
    },

    //树点击事件
    getNode(data, node, obj) {
      this.classId = data.id
      this.queryParams.classificationId = data.id
      this.getList()
    },
    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      otherProjectList(this.queryParams).then(response => {
        this.projectInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    close(data) {
      this.type = 0
      this.queryParams.classificationId = null;
      this.open = data;
      this.classId = null;
      this.getList();
    },

    closeDetail(data) {
      this.type = 0
      this.open = data;
      this.getList();
    },
    //售后管理确认按钮
    handleChange() {
      const projectIds = this.ids;
      if (projectIds.length === 0) {
        this.$modal.msgError("请选择项目");
      } else {
        selectProjectContract(projectIds).then(res => {
          this.projectBySales = res.data;
          this.$emit("ok", this.projectBySales)
        })
      }
    },
    //项目名称跳转
    handleClick(row, index) {
      this.edit = "details"
      this.reset();
      this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index
      this.id = row.projectId;
      this.type = 1
      //this.reset();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        classificationId: null,
        projectNumber: null,
        projectName: null,
        contractId: null,
        contractName: null,
        projectLeaderId: null,
        projectLeader: null,
        executorId: null,
        executorName: null,
        startTime: null,
        endTime: null,
        attackTime: null,
        completeTime: null,
        state: null,
        operateTime: null,
        operateId: null,
        operateName: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        creationId: null,
        creationName: null,
        creationTime: null,
        belongTo: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (!this.isSale){
        this.listDeliverProject();
      }else {
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加项目信息";
      this.edit = "add"
      this.type = 1
    },
    /** 修改按钮操作 */
    handleUpdate(row, index) {
      this.reset();
      this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index
      this.edit = "edit"
      this.id = row.projectId;
      if (row.projectType == "1" || row.projectType == "2") {
        this.type = 1
      } else {
        this.type = 3
      }
      // const projectId = row.projectId || this.ids
      // getProjectInfo(projectId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改项目信息";
      // });
    },
    /** 项目保存按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateProjectInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.state = 0;
            this.form.delFlag = 0;
            addProjectInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目名称为"' + row.projectName + '"的数据项？').then(function () {
        return delProjectInfo(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 提交按钮操作 */
    submitState(row) {
      this.form.projectId = row.projectId
      this.form.state = 1
      this.$modal.confirm('提交后不能再修改，是否确认提交项目名称为"' + row.projectName + '"的数据项？').then(function () {

      }).then(() => {
        updateProjectInfo(this.form).then(response => {
          this.getList();
          this.$modal.msgSuccess("提交成功");
        });

      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/projectInfo/export', {
        ...this.queryParams
      }, `projectInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
